<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="合同名称" prop="contractTitle">
        <el-input
          v-model="queryParams.contractTitle"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['contract:contractInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractInfoList" @selection-change="handleSelectionChange">
      <el-table-column label="合同名称" align="center" prop="contractTitle" min-width="180" show-overflow-tooltip />
      <el-table-column label="发起方" align="center" prop="organizationName" min-width="200" show-overflow-tooltip />
      <el-table-column label="参与方" align="center" prop="receiverOrganizationName" min-width="200" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <el-popover
            placement="bottom"
            popper-class="table-popper"
            :title="'参与方（'+row.signings.length+')'"
            width="230"
            trigger="hover">
            <div class="signings">
              <div class="signings-item" v-for="item in row.signings" :key="item.signingId">
                <div class="company_name">
                  {{item.organizationName}}
                </div>
                <div class="signing_status">
                  <span v-if="item.contractSignStatus === 1" style="cursor: pointer;color:#909399;">待签署</span>
                  <span v-else-if="item.contractSignStatus === 2" style="cursor: pointer;color:#11A983;">签署成功</span>
                  <span v-else-if="item.contractSignStatus === 3" style="cursor: pointer;color:#F56C6C;">签署失败</span>
                </div>
              </div>
            </div>
            <span slot="reference" style="cursor: pointer">{{row.receiverOrganizationName}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="签署状态" align="center" prop="contractStatus" width="100">
        <template slot-scope="{ row }">
          <el-tag v-if="row.contractStatus === 1" type="info">待签署</el-tag>
          <el-tag v-else-if="row.contractStatus === 2" type="warning">部分签署</el-tag>
          <el-tag v-else-if="row.contractStatus === 3">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="center" prop="createTime" width="180" />
      <el-table-column label="完成时间" align="center" prop="completionTime" width="180" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more-outline"
            @click="handleSigning(scope.row)"
            v-hasPermi="['contract:contractInfo:signingList']"
          >参与人员</el-button>

          <el-dropdown @command="(command)=>handleCommand(command,scope.row)">
            <el-button size="mini" type="text">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="view" >查看合同</el-dropdown-item>
              <el-dropdown-item command="download" >下载合同</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同对话框 -->
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" destroy-on-close append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板" prop="templateId">
          <el-select v-model="form.templateId">
            <el-option v-for="item in templateList" :value="item.templateId" :key="item.templateId" :label="item.templateName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="saveLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" :loading="saveLoading">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="参与人员" :visible.sync="signingOpen" width="50%" destroy-on-close append-to-body>
      <contract-signing v-if="signingOpen" :contractId="form.contractId"></contract-signing>
    </el-dialog>
  </div>
</template>

<script>
import {listContractInfo, addContractInfo, listOtherContractInfo} from "@/api/contract/contractInfo"
import { listTemplate } from "@/api/contract/template.js"
import ContractSigning from "@/views/contract/contractSigning/index.vue";
export default {
  name: "ContractInfo",
  components: {ContractSigning},
  props:{
    organizationId:{
      type:String,
    },
    initiateOrganizationId:{
      type:String,
    },
    type:{
      type:Number,
    }
  },
  data() {
    return {
      signingOpen:false,
      // 遮罩层
      loading: true,
      saveLoading:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同表格数据
      contractInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type:null,
        contractTitle: null,
        templateId: null,
        organizationId: null,
        contractStatus: null,
        completionTime: null,
        receiverOrganizationId:null,
      },
      templateList:[],
      // 表单参数
      form: {
        contractId:null,
      },
      // 表单校验
      rules: {
        templateId:[
          {required:true, message:"请选择合同模板", trigger: ['blur','change']},
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询合同列表 */
    getList() {
      this.loading = true
      if (this.queryParams.receiverOrganizationId){
        listOtherContractInfo(this.queryParams).then(response => {
          this.contractInfoList = response.rows
          this.total = response.total
          this.loading = false
        })
      }else{
        listContractInfo(this.queryParams).then(response => {
          this.contractInfoList = response.rows
          this.total = response.total
          this.loading = false
        })
      }

    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractTitle: null,
        templateId: null,
        organizationId: null,
        contractStatus: null,
        completionTime: null,
        createTime: null,
        updateTime: null,
        receiverOrganizationId:this.organizationId
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      listTemplate({ pageSize: 100,type:this.type }).then(response=>{
        this.templateList = response.rows
      })
      this.reset()
      this.open = true
      this.title = "添加合同"
    },
    /** 修改按钮操作 */
    handleSigning(row) {
      this.form.contractId = row.contractId
      this.signingOpen = true
    },
    handleCommand(command,row){
      if (row.type === 2){
        row.viewPdfUrl = process.env.VUE_APP_BASE_API + row.viewPdfUrl
        row.downloadUrl = process.env.VUE_APP_BASE_API + row.downloadUrl
      }
      if (command === "view"){
        window.open(row.viewPdfUrl)
      }else if(command === "download"){
        // 创建a标签元素
        const a = document.createElement("a");

        // 设置下载属性（HTML5特性）
        a.download = ""; // 可设置为自定义文件名，如a.download = "文件名称.pdf"

        // 设置链接地址
        a.href = row.downloadUrl;

        // 将a标签添加到文档中
        document.body.appendChild(a);

        // 触发点击事件开始下载
        a.click();

        // 下载完成后移除a标签（避免内存泄漏）
        document.body.removeChild(a);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveLoading = true
          addContractInfo(this.form).then(response => {
            this.saveLoading = false
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.getList()
          }).catch(()=>{
            this.saveLoading = false
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids
      this.$modal.confirm('是否确认删除合同编号为"' + contractIds + '"的数据项？').then(function() {
        return delContractInfo(contractIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('contract/contractInfo/export', {
        ...this.queryParams
      }, `contractInfo_${new Date().getTime()}.xlsx`)
    }
  },
  watch:{
    initiateOrganizationId:{
      handler(val){
        if (val){
          // console.log(this.organizationId)
          this.queryParams.organizationId = this.organizationId
          this.queryParams.receiverOrganizationId = val
        }
      },
      immediate:true
    }
  }
}
</script>

<style scoped lang="scss">

</style>
<style lang="scss">
.table-popper {
  .el-popover__title {
    font-size: 12px !important;
    margin-bottom: 10px !important;
  }
  .signings-item{
    height: 35px;
    display: flex;
    font-size: 12px;
    margin-bottom: 5px;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #c0c4cc4f;
    .company_name{
      width: 70%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .signing_status{
      width: 25%;
    }
  }
}
</style>
